package com.edroid.droidhelper.pc.view;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

import net.miginfocom.swing.MigLayout;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.edroid.droidhelper.pc.app.Bootstrup;
import com.edroid.droidhelper.pc.model.AppGlobal;
import com.edroid.droidhelper.pc.model.AppPrefes;
import com.edroid.droidhelper.pc.model.NetwokWorker;
import com.edroid.droidhelper.pc.model.Res;
import com.edroid.droidhelper.pc.util.HttpUtils;
import com.edroid.droidhelper.pc.util.SecurityUtil;
import com.edroid.droidhelper.pc.util.TextUtils;

public class LoginDialog extends JDialog {
	private static final long serialVersionUID = 1L;
	
	private final JPanel contentPanel = new JPanel();
	private JTextField editUsername;
	private JTextField editPassword;
	private JCheckBox checkBoxSavePassword, checkBoxAutoLogin;
	private JButton btnLogin;
	private boolean logout;
	
	
	private void close() {
//		saveParams();

		dispose();
	}
	
	private final WindowAdapter mWindowListener = new WindowAdapter() {

		@Override
		public void windowOpened(WindowEvent e) {
			System.out.println("0");
		}

		@Override
		public void windowClosing(WindowEvent e) {
			System.out.println("1");
			saveParams();
		}

		@Override
		public void windowClosed(WindowEvent e) {
			System.out.println("2");
			
			dispose();
			
			Bootstrup.getInstance().cleanup();
			
			System.exit(0);
		}
	};

	/**
	 * Create the dialog.
	 */
	public LoginDialog(boolean logout) {
		this.logout = logout;
		
		setIconImage(Res.getImage("/res/drawable/ic_buddy.png"));
		setResizable(false);
		setTitle("用户登录");
		setBounds(100, 100, 404, 397);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		addWindowListener(mWindowListener);
		
		getContentPane().setLayout(new BorderLayout());
		
		JLabel lblTest = new JLabel("", new ImageIcon(Res.getImage("/res/drawable/title.png")), SwingConstants.CENTER);
		getContentPane().add(lblTest, BorderLayout.NORTH);
	
		contentPanel.setBorder(new EmptyBorder(20, 30, 20, 30));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		
		contentPanel.setLayout(new MigLayout("", "[]5[grow][]", "[]5[]5[]10[]"));
		{
			JLabel label = new JLabel("用户名：");
			contentPanel.add(label, "cell 0 0");

			editUsername = new JTextField();
			contentPanel.add(editUsername, "cell 1 0 2 1,growx");
			editUsername.setColumns(10);
		}
		{
			JLabel label = new JLabel("密码：");
			contentPanel.add(label, "cell 0 1");
			
			editPassword = new JPasswordField();
			contentPanel.add(editPassword, "cell 1 1 2 1,growx");
			editPassword.setColumns(10);
		}
		{
			checkBoxSavePassword = new JCheckBox("记住密码");
			contentPanel.add(checkBoxSavePassword, "cell 2 2");
		}
		{
			checkBoxAutoLogin = new JCheckBox("自动登陆");
			contentPanel.add(checkBoxAutoLogin, "cell 0 2 3 1");
		}
		
		{
			btnLogin = new JButton("登陆");
			btnLogin.setIcon(new ImageIcon(Res.getImage("/res/drawable/ic_buddy.png")));
			btnLogin.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					checkLogin();
				}
			});
			
			contentPanel.add(btnLogin, "cell 0 3 3 1,growx");
		}
		
		readParams();
	}
	
	private void saveParams() {
		AppPrefes.putBoolean("chk.save_password", checkBoxSavePassword.isSelected());
		AppPrefes.putBoolean("chk.auto_login", checkBoxAutoLogin.isSelected());
		
        AppPrefes.put("username", editUsername.getText());
        AppPrefes.put("password", SecurityUtil.encrypt(editPassword.getText()));
        
        AppPrefes.applay();
	}
	
	public static void loginOut() {
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				LoginDialog dialog = new LoginDialog(true);
				dialog.setVisible(true);
			}
		});
	}
	
	public static void startLogin() {
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				LoginDialog dialog = new LoginDialog(false);
				dialog.setVisible(true);
			}
		});
	}

	private void readParams() {
		checkBoxSavePassword.setSelected(AppPrefes.getBoolean("chk.save_password", false));
		
		String username = AppPrefes.get("username", null);
		String password = SecurityUtil.decrypt(AppPrefes.get("password", null));
		editUsername.setText(username);
		
		if(checkBoxSavePassword.isSelected()) { //要记住密码，才能自动登录嘛
			editPassword.setText(password);
			
			if(logout) {
				checkBoxAutoLogin.setSelected(false);
			} else {
				checkBoxAutoLogin.setSelected(AppPrefes.getBoolean("chk.auto_login", false));
				if(checkBoxAutoLogin.isSelected() && !TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
					login(username, password);
				} else {
					checkBoxAutoLogin.setSelected(false);
				}
			}
		}
	}
	
	private void errorDialog(String msg) {
		JOptionPane.showMessageDialog(null, msg, "提示", JOptionPane.ERROR_MESSAGE);
	}
	
	private void checkLogin() {
		String username = editUsername.getText();
		String password = editPassword.getText();
		
		if(TextUtils.isEmpty(password)) {
			errorDialog("密码不能为空");
			return;
		}
		if(TextUtils.isEmpty(username)) {
			errorDialog("用户名不能为空");
			return;
		}
		
		login(username, password);
	}
	
	private void login(final String username, final String password) {
		NetwokWorker.post(new Runnable() {
			
			@Override
			public void run() {
				login_r(username, password);
			}
		});
	}
	
	private void login_r(String username, String password) {
		btnLogin.setEnabled(false);
		btnLogin.setText("登录中...");

		if (AppGlobal.DEBUG_ON) {
			AppGlobal.username = username;
			AppGlobal.userid = "1000";
			Bootstrup.getInstance().showMainWindow();
			close();

			return;
		}

		try {
			String ret = HttpUtils.post(AppGlobal.API_URL_LOGIN, 
					new BasicNameValuePair("business.username", username), 
					new BasicNameValuePair("business.password", password));
			if (ret != null) {
				JSONObject jsonObject = new JSONObject(ret);
				int code = jsonObject.getInt("code");
				if (code == 200) {
					AppGlobal.username = username;

					SwingUtilities.invokeLater(new Runnable() {
						
						@Override
						public void run() {
							Bootstrup.getInstance().showMainWindow();
							
							close();
						}
					});

					return;
				} else {
					errorDialog("登录失败 " + code + "\n" + jsonObject.getString("msg"));
				}
			} else {
				errorDialog("登录失败，服务器响应错误！ ");
			}
		} catch (Exception e) {
			e.printStackTrace();

			errorDialog("登录失败\n" + e.getMessage());
		}

		btnLogin.setEnabled(true);
		btnLogin.setText("登录");
	}
		
}
